package com.amado.course40Reflect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by Administrator on 2018/1/4.
 */
public class S05DynamicProxy {
	public static void main(String[] args) {
		User user = new UserImpl();
		User proxy1 = (User) Proxy.newProxyInstance(S05DynamicProxy.class.getClassLoader(), new Class[] { User.class },
				new TimeHandler(user));
		proxy1.getUser(1);
//		User proxy2 = (User) Proxy.newProxyInstance(ProxyTest.class.getClassLoader(), new Class[] { User.class },
//				new InvocationHandler() {
//
//					@Override
//					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//						System.out.println("time being");
//						long startTime = System.currentTimeMillis();
//						Object returnObject = method.invoke(user, args);
//						System.out.println("time end");
//						long endTime = System.currentTimeMillis();
//						System.out.println("耗时MS " + (endTime - startTime));
//						return returnObject;
//					}
//				});
		
	}
}

class TimeHandler implements InvocationHandler {
	private Object subject;

	public TimeHandler(Object subject) {
		this.subject = subject;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		if(method.getName().equals("asdfas")){
			return  method.invoke(subject, args);
		}
		System.out.println("time being");
		long startTime = System.currentTimeMillis();
		Object returnObject = method.invoke(subject, args);
		System.out.println("time end");
		long endTime = System.currentTimeMillis();
		System.out.println("耗时MS " + (endTime - startTime));
		return returnObject;
	}
}

class UserImpl implements User {
	@Override
	public String getUser(long id) {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("do something");
		return id + "name";
	}
}